<script setup lang="ts">
import * as THREE from 'three';
import { onMounted, onUnmounted } from 'vue';
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";

// 初始化场景
const scene = new THREE.Scene();
// 设置相机
const camera = new THREE.PerspectiveCamera(
  75, //视角
  window.innerWidth / window.innerHeight, //宽高比
  0.1, // 近平面
  1000 // 远平面
);
// 创建渲染器
const renderer = new THREE.WebGLRenderer({
  antialias: true, //设置抗锯齿
});

// 添加轨道控制器(控制的是相机)
const controls = new OrbitControls(camera, renderer.domElement);
// 设置带阻尼的惯性
controls.enableDamping = true;
// 设置阻尼系数，系数越小惯性越大
controls.dampingFactor = 0.05;
// 鼠标控制
controls.mouseButtons = {
  //左键平移
  LEFT: THREE.MOUSE.PAN,
  //滚轮滑动
  MIDDLE: THREE.MOUSE.DOLLY,
  //右键旋转
  RIGHT: THREE.MOUSE.ROTATE,
};

onMounted(() => {
  // 添加到界面中
  document.body.appendChild(renderer.domElement);
  // 监听窗口变化更新renderer
  window.addEventListener("resize", resize);
  render();
  resize();


  scene.add(createCube());
  camera.position.set(2, 2, 5);
  camera.lookAt(0, 0, 0);
});

const createCube = (): THREE.Mesh => {
  // 创建几何体
  const geometry = new THREE.BoxGeometry(1, 1, 1);
  // 创建材质
  const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
  // 创建网格
  const cube = new THREE.Mesh(geometry, material);
  return cube;
}


const resize = () => {
  renderer.setSize(window.innerWidth, window.innerHeight);
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
}
// 循环渲染
const render = () => {
  controls.update();
  // 每帧执行此函数
  requestAnimationFrame(render);
  // 渲染
  renderer.render(scene, camera);
}

</script>

<template>
  <div></div>
</template>

<style scoped>
/* 设置画布canvas铺满，并位于左上角 */
canvas {
  width: 100vw;
  height: 100vh;
  position: fixed;
  left: 0;
  top: 0;
}
</style>